<template>
    <div class="map-container" v-loading="loading">

        <div class="map-header-left">
            <template v-if="mapHistory.length > 0">
                <span v-for="(item, index) in mapHistory" :key="index">
                    <span v-if="index >= 1">
                        {{ item.area }}-
                    </span>
                </span>
                {{ currentArea }}
            </template>
        </div>
        <div class="map-header" v-if="currentLevel !== 'china'">
            <button class="back-button" @click="handleBack"><i class="el-icon-fanhuishangyiji"
                    style="color: #666;margin-right: 5px;" />返回</button>
        </div>
        <div v-if="!showDistrictMap" ref="chartContainer" class="chart-container"></div>
        <div v-else ref="chartContainer" class="chart-container district-map"></div>
        <!-- <div v-if="loading" class="loading">加载中...</div> -->
        <!-- <div v-if="error" class="error">{{ error }}</div> -->
    </div>
</template>

<script>
import * as echarts from 'echarts'
import axios from 'axios'
import { getRegionMap } from '@/api/user'

// 加载高德地图
const AMap = window.AMap

export default {
    name: 'ChinaMap',
    data() {
        return {
            chart: null,
            currentLevel: 'china', // 当前地图层级：china, province, city
            currentArea: '', // 当前选中的区域
            mapData: {}, // 地图数据
            loading: true,
            error: null,
            areaCodes: {}, // 存储地区编码
            areaName: '中国',
            districtMap: null, // 区级地图实例
            showDistrictMap: false, // 是否显示区级地图
            // 模拟数据
            mockData: {
                china: {
                    name: '中国',
                    children: [
                        {
                            name: '北京', value: 800, children: [
                                { name: '东城区', value: 300 },
                                { name: '西城区', value: 400 },
                                { name: '朝阳区', value: 500 }
                            ]
                        },
                        {
                            name: '上海', value: 900, children: [
                                { name: '浦东新区', value: 600 },
                                { name: '黄浦区', value: 400 },
                                { name: '徐汇区', value: 300 }
                            ]
                        },
                        {
                            name: '广东', value: 1000, children: [
                                {
                                    name: '广州', value: 800, children: [
                                        { name: '天河区', value: 500 },
                                        { name: '海珠区', value: 400 }
                                    ]
                                },
                                {
                                    name: '深圳', value: 900, children: [
                                        { name: '南山区', value: 600 }
                                    ]
                                }
                            ]
                        },
                        {
                            name: '浙江', value: 950, children: [
                                {
                                    name: '杭州', value: 850, children: [
                                        { name: '西湖区', value: 600 },
                                        { name: '滨江区', value: 500 }
                                    ]
                                },
                                {
                                    name: '宁波', value: 750, children: [
                                        { name: '海曙区', value: 400 },
                                        { name: '江北区', value: 350 }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            },
            guojiaData: null,
            mapCenter: null,
            // 历史记录栈
            mapHistory: [],
            chinaMapData: null,
            isMunicipality: false,
        }
    },
    async mounted() {
        try {
            this.loading = true
            this.error = null

            // 1. 加载地区编码数据
            await this.loadAreaCodes()

            // 2. 加载地图数据
            await this.loadChinaMap()

            // 3. 初始化图表
            this.initChart()

            // 4. 渲染地图
            this.renderMap()

            this.loading = false

            this.chinaMapData = await this.getEMapData('getRegionMapData', '', 'country', '', '', '', '')
        } catch (error) {
            console.error('初始化失败:', error)
            this.error = '加载失败，请刷新页面重试'
            this.loading = false
        }
    },
    methods: {
        async getEMapData(url = 'getRegionMapData', yearNo = '', regionType = 'country', regionName, provinceName, cityName, districtName) {
            const res = await getRegionMap(url, yearNo = '', regionType, regionName, provinceName, cityName, districtName)
            return res.data
        },
        async loadAreaCodes() {
            try {
                const response = await axios.get('https://geo.datav.aliyun.com/areas_v3/bound/all.json')
                if (!response.data) {
                    throw new Error('地区编码数据为空')
                }
                this.areaCodes = this.processAreaCodes(response.data)
            } catch (error) {
                console.error('加载地区编码数据失败:', error)
                throw error
            }
        },
        processAreaCodes(data) {
            const codes = {
                provinces: {},
                cities: {}
            }

            data.forEach(province => {
                codes.provinces[province.name] = province.adcode
                if (province.children) {
                    codes.cities[province.name] = province.children.map(city => city.name)
                }
            })

            return codes
        },
        getProvinceCode(provinceName) {
            return this.areaCodes.provinces[provinceName]
        },
        async loadChinaMap() {
            try {
                const response = await axios.get('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
                if (!response.data) {
                    throw new Error('地图数据为空')
                }
                this.guojiaData = response
                echarts.registerMap('china', response.data)

                // 生成完整的中国地图数据
                const chinaData = {
                    name: '中国',
                    // children: response.data.features.map(feature => ({
                    //     name: feature.properties.name,
                    //     value: Math.floor(Math.random() * 1000)
                    // })),
                    children: (await this.getEMapData('getRegionMapData', '', 'country', '', '', '', '')) || response.data.features.map(feature => ({
                        name: feature.properties.name,
                        value: Math.floor(Math.random() * 1000)
                    })),
                }
                // console.log('chinaData', chinaData)
                // 设置当前地图数据
                this.currentLevel = 'china'
                this.currentArea = '中国'
                this.mapData = chinaData

                // 保存初始状态到历史记录
                this.mapHistory.push({
                    level: 'china',
                    area: '中国',
                    data: JSON.parse(JSON.stringify(chinaData))
                })

                console.log('初始化中国地图数据:', {
                    level: this.currentLevel,
                    area: this.currentArea,
                    mapData: this.mapData
                })
            } catch (error) {
                console.error('加载地图数据失败:', error)
                throw error
            }
        },
        async loadProvinceMap(provinceName) {
            try {
                const response = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${this.getProvinceCode(provinceName)}_full.json`)
                if (!response.data) {
                    throw new Error('省份地图数据为空')
                }
                echarts.registerMap(provinceName, response.data)
            } catch (error) {
                console.error('加载省份地图数据失败:', error)
                throw error
            }
        },
        async loadCityMap(cityName) {
            try {
                const response = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${this.getCityCode(cityName)}_full.json`)
                if (!response.data) {
                    throw new Error('城市地图数据为空')
                }
                echarts.registerMap(cityName, response.data)
            } catch (error) {
                console.error('加载城市地图数据失败:', error)
                throw error
            }
        },
        initChart() {
            if (this.chart) {
                this.chart.dispose()
            }
            this.chart = echarts.init(this.$refs.chartContainer)

            // 添加窗口大小变化的处理
            window.addEventListener('resize', () => {
                if (this.chart) {
                    this.chart.resize()
                    // 重新设置当前配置
                    const currentOption = this.chart.getOption()
                    this.chart.setOption(currentOption)
                }
            })

            // 绑定点击事件
            this.chart.on('click', (params) => {
                this.handleMapClick(params)
            })
            this.chart.on('dblclick', () => {
                this.handleBack()
            });
        },
        async loadMapData(area) {
            try {
                // 根据当前层级获取对应的模拟数据
                let data = this.mockData[area]
                if (!data) {
                    // 如果找不到对应数据，生成随机数据
                    data = {
                        name: area,
                        children: Array(5).fill(0).map((_, index) => ({
                            name: `地区${index + 1}`,
                            value: Math.floor(Math.random() * 1000)
                        }))
                    }
                }

                this.mapData = data
                return data
            } catch (error) {
                console.error('加载地图数据失败:', error)
                throw error
            }
        },
        getMapOption(mapName, zoom = 2.5, top = '8%') {
            console.log('mapName', mapName)
            console.log('zoom', zoom)
            console.log('top', top)
            return {
                animation: true,
                animationDuration: 300,
                animationEasing: 'cubicOut',
                tooltip: {
                    trigger: 'item',
                    backgroundColor: 'rgba(136,119,9,0.78)',
                    borderColor: '#ccc',
                    borderWidth: 1,
                    padding: [10, 15],
                    textStyle: {
                        color: '#ffffff'
                    },
                    formatter: (params) => {
                        const data = params.data || {}
                        const formatNumber = (num) => {
                            return num ? Number(num).toLocaleString('zh-CN') : '0'
                        }
                        return `${params.name}<br/>
                        销售完成金额：${formatNumber(data.salesAmt)}<br/>
                        经销商出货金额：${formatNumber(data.outboundAmt)}<br/>
                        终端进货金额：${formatNumber(data.terminalSignAmt)}<br/>
                        费用投入金额：${formatNumber(data.costAmt)}<br/>
                        开瓶瓶数：${formatNumber(data.openCnt)}<br/>
                        异地瓶数：${formatNumber(this.currentLevel === 'province' ? data.provinceOverAreaLocalOpenCnt : this.currentLevel === 'city' ? data.cityOverAreaLocalOpenCnt : data.districtOverAreaLocalOpenCnt)}<br/>
                        `
                    }
                },
                visualMap: {
                    type: 'piecewise',
                    pieces: [
                        { min: 100.0001, label: '好', color: '#ee6666' },
                        { min: 80, max: 100, label: '正常', color: '#fac858' },
                        { max: 79.9999, label: '差', color: '#91cc75' }
                    ],
                    left: '27%',
                    bottom: '20%',
                    textStyle: {
                        color: '#000'
                    },
                    silent: true,
                    z: 10
                },
                geo: {
                    map: mapName,
                    roam: 'move',
                    zoomLock: true,
                    scaleLimit: {
                        min: 1,
                        max: 5
                    },
                    zoom: zoom,
                    top: top,
                    layoutCenter: ['50%', mapName === 'china' ? '58%' : '50%'],
                    layoutSize: mapName === 'china' ? '85%' : '60%',
                    itemStyle: {
                        areaColor: 'rgba(163, 1, 1, 1)',
                        shadowColor: 'rgb(163, 1, 1)',
                        shadowOffsetY: 3
                    },
                    select: {
                        itemStyle: {
                            areaColor: 'rgba(163, 1, 1, 0.3)',
                            shadowColor: 'rgb(163, 1, 1)',
                            shadowOffsetY: 3
                        }
                    },
                    emphasis: {
                        itemStyle: {
                            areaColor: 'rgba(163, 1, 1, 0.3)',
                            shadowColor: 'rgb(163, 1, 1)',
                            shadowOffsetY: 3
                        }
                    },
                    regions: [{
                        name: '南海诸岛',
                        silent: true,
                        itemStyle: {
                            areaColor: 'rgba(255, 141, 141, 1)',
                            shadowColor: 'transparent',
                            shadowOffsetY: 0
                        },
                        select: {
                            itemStyle: {
                                areaColor: 'rgba(255, 141, 141, 1)',
                                shadowColor: 'transparent',
                                shadowOffsetY: 0
                            }
                        },
                        emphasis: {
                            itemStyle: {
                                areaColor: 'rgba(255, 141, 141, 1)',
                                shadowColor: 'transparent',
                                shadowOffsetY: 0
                            }
                        }
                    }],
                    z: 1,
                    show: true
                },
                series: [{
                    name: '数据',
                    type: 'map',
                    geoIndex: -1,
                    map: mapName,
                    roam: 'move',
                    zoom: zoom,
                    top: top,
                    layoutCenter: ['50%', mapName === 'china' ? '58%' : '50%'],
                    layoutSize: mapName === 'china' ? '85%' : '60%',
                    z: 2,
                    label: {
                        show: true,
                        color: '#000',
                        fontSize: 14
                    },
                    select: {
                        itemStyle: {
                            areaColor: 'transparent',
                            borderColor: '#ffffff',
                            borderWidth: 1
                        },
                        label: {
                            show: true,
                            color: '#000',
                            fontSize: 14
                        }
                    },
                    emphasis: {
                        label: {
                            show: true,
                            color: '#000',
                            fontSize: 14
                        },
                        itemStyle: {
                            areaColor: 'rgba(169, 17, 17, 0.5)',
                            borderColor: '#ffffff',
                            borderWidth: 1,
                            color: '#fff'
                        }
                    },
                    itemStyle: {
                        areaColor: 'transparent',
                        borderColor: '#ffffff',
                        borderWidth: 1
                    },
                    data: this.mapData.children,
                    zlevel: 2
                }]
            }
        },
        renderMap() {
            if (!this.chart) {
                throw new Error('图表未初始化')
            }

            console.log('渲染地图 - 当前状态:', {
                level: this.currentLevel,
                area: this.currentArea,
                mapData: this.mapData,
                chartInstance: this.chart
            })

            const option = this.getMapOption(
                this.currentLevel === 'china' ? 'china' : this.currentArea,
                this.currentLevel === 'china' ? 1 : 1,
                this.currentLevel === 'china' ? '20%' : '8%'
            )

            console.log('渲染配置:', option)

            let listener = function () {
                if (this.chart) {
                    this.chart.resize();
                }
            };
            this.chart.setOption(option, {
                animation: true,
                animationDuration: 300,
                animationEasing: 'cubicOut'
            })
            // EleResize.on(this.$refs.chartContainer, listener);
        },
        async handleMapClick(params) {
            const clickedArea = params.name
            console.log('点击区域:', clickedArea, this.currentLevel)

            if (this.currentLevel === 'china') {
                try {
                    this.loading = true
                    // 判断是否是直辖市
                    const isMunicipality = ['北京市', '上海市', '天津市', '重庆市', '香港特别行政区', '澳门特别行政区', '台湾省'].includes(clickedArea)
                    this.isMunicipality = isMunicipality
                    // 获取省份的地图数据
                    const provinceCode = this.getProvinceCode(clickedArea)
                    if (!provinceCode) {
                        throw new Error(`未找到省份 ${clickedArea} 的编码`)
                    }

                    const response = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${provinceCode}_full.json`)
                    if (!response.data) {
                        throw new Error('省份地图数据为空')
                    }
                    console.log('省份地图数据:', response.data)
                    // 注册省份地图
                    echarts.registerMap(clickedArea, response.data)
                    // 生成省份的模拟数据
                    const provinceData = {
                        name: clickedArea,
                        children: (await this.getEMapData('getRegionMapData', '', isMunicipality ? 'city' : 'province', '', clickedArea, '', '')) || response.data.features.map(feature => ({
                            name: feature.properties.name,
                            value: Math.floor(Math.random() * 1000)
                        })),
                    }

                    // 保存当前状态到历史记录
                    this.mapHistory.push({
                        level: this.currentLevel,
                        area: this.currentArea,
                        data: JSON.parse(JSON.stringify(this.mapData))
                    })
                    console.log('保存历史记录:', this.mapHistory)

                    // 先更新状态
                    this.currentLevel = isMunicipality ? 'city' : 'province'
                    this.currentArea = clickedArea
                    this.areaName = clickedArea
                    this.mapData = provinceData
                    this.$emit('map-click', { name: clickedArea, level: 'province' })

                    // 等待一帧以确保状态更新
                    await this.$nextTick()

                    // 根据省份调整缩放和位置
                    const zoom = clickedArea === '海南省' ? 5 : clickedArea === '香港特别行政区' || clickedArea === '澳门特别行政区' || clickedArea === '台湾省' ? 1 : 1
                    const top = clickedArea === '海南省' ? '75%' : clickedArea === '香港特别行政区' || clickedArea === '澳门特别行政区' || clickedArea === '台湾省' ? '15%' : '8%'

                    const option = this.getMapOption(clickedArea, zoom, top)
                    this.chart.setOption(option, {
                        animation: true,
                        animationDuration: 300,
                        animationEasing: 'cubicOut',
                        notMerge: true,
                        replaceMerge: ['geo', 'series']
                    })

                } catch (error) {
                    console.error('加载省份地图失败:', error)
                    this.error = '加载省份地图失败'
                    // 发生错误时，移除最后一条历史记录
                    this.mapHistory.pop()
                } finally {
                    this.loading = false
                }
            } else if (this.currentLevel === 'province') {
                try {
                    this.loading = true
                    // 判断是否是直辖市或特别行政区
                    const isMunicipality = ['北京市', '上海市', '天津市', '重庆市', '香港特别行政区', '澳门特别行政区', '台湾省'].includes(this.currentArea)

                    // 获取城市的地图数据
                    const cityCode = this.getProvinceCode(clickedArea)
                    if (!cityCode) {
                        throw new Error(`未找到城市 ${clickedArea} 的编码`)
                    }

                    const response = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${cityCode}_full.json`)
                    if (!response.data) {
                        throw new Error('城市地图数据为空')
                    }

                    // 注册城市地图
                    echarts.registerMap(clickedArea, response.data)

                    // 生成城市的模拟数据
                    const cityData = {
                        name: clickedArea,
                        children: (await this.getEMapData('getRegionMapData', '', 'city', '', this.currentArea, clickedArea, '')) || response.data.features.map(feature => ({
                            name: feature.properties.name,
                            value: Math.floor(Math.random() * 1000)
                        })),
                    }

                    // 保存当前状态到历史记录
                    this.mapHistory.push({
                        level: this.currentLevel,
                        area: this.currentArea,
                        data: JSON.parse(JSON.stringify(this.mapData))
                    })
                    console.log('保存历史记录:', this.mapHistory)

                    // 先更新状态
                    this.currentLevel = 'city'
                    this.currentArea = clickedArea
                    this.areaName = clickedArea
                    this.mapData = cityData

                    this.$emit('map-click', { name: clickedArea, level: 'city' })

                    // 如果是直辖市或特别行政区的分区，切换到map地图
                    if (isMunicipality) {
                        this.loading = true
                        await this.initDistrictMap(clickedArea, response.data)
                    } else {
                        // 等待一帧以确保状态更新
                        await this.$nextTick()
                        // 根据省份调整缩放和位置
                        const zoom = clickedArea === '海南省' ? 5 : clickedArea === '香港特别行政区' || clickedArea === '澳门特别行政区' || clickedArea === '台湾省' ? 1 : 1
                        const top = clickedArea === '海南省' ? '10%' : clickedArea === '香港特别行政区' || clickedArea === '澳门特别行政区' || clickedArea === '台湾省' ? '15%' : '8%'

                        const option = this.getMapOption(clickedArea, zoom, top)

                        // 渲染城市地图
                        // const option = this.getMapOption(clickedArea, 1, '8%')
                        this.chart.setOption(option, {
                            animation: true,
                            animationDuration: 300,
                            animationEasing: 'cubicOut',
                            notMerge: true,
                            replaceMerge: ['geo', 'series']
                        })
                    }

                } catch (error) {
                    console.error('加载城市地图失败:', error)
                    this.error = '加载城市地图失败'
                    // 发生错误时，移除最后一条历史记录
                    this.mapHistory.pop()
                } finally {
                    this.loading = false
                }
            } else if (this.currentLevel === 'city') {
                try {
                    this.loading = true
                    // 获取区县的地图数据
                    const districtCode = this.getProvinceCode(clickedArea)
                    if (!districtCode) {
                        throw new Error(`未找到区县 ${clickedArea} 的编码`)
                    }

                    // 使用区县编码获取地图数据
                    const response = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${districtCode}.json`)
                    if (!response.data) {
                        throw new Error('区县地图数据为空')
                    }

                    // 保存当前状态到历史记录
                    this.mapHistory.push({
                        level: this.currentLevel,
                        area: this.currentArea,
                        data: JSON.parse(JSON.stringify(this.mapData))
                    })

                    // 更新状态
                    this.currentArea = clickedArea
                    this.areaName = clickedArea

                    // 切换到区级地图显示
                    this.loading = true
                    await this.initDistrictMap(clickedArea, response.data)

                    // 触发地图点击事件
                    this.$emit('map-click', { name: clickedArea, level: 'area' })

                } catch (error) {
                    console.error('加载区县地图失败:', error)
                    this.error = '加载区县地图失败'
                    // 发生错误时，移除最后一条历史记录
                    this.mapHistory.pop()
                } finally {
                    this.loading = false
                }
            }
        },
        async initDistrictMap(cityName, geoData) {
            try {
                console.log('初始化区级地图:', cityName, geoData)
                // 销毁echarts实例
                if (this.chart) {
                    this.chart.dispose()
                    this.chart = null
                }
                const provinceName = this.mapHistory.slice(-2)[0].area
                const cityNames = this.mapHistory.slice(-1)[0].area
                console.log(this.currentLevel, "this.currentLevel")
                const cityData = await getRegionMap('getRegionMapAreaCustomer', '', '', '', this.isMunicipality ? cityNames : provinceName, cityNames, this.currentArea)
                console.log('城市数据:', cityData)
                // 获取当前区县的编码
                const getDistrictCode = async (districtName) => {
                    try {
                        const response = await axios.get('https://geo.datav.aliyun.com/areas_v3/bound/all.json')
                        console.log('地区编码数据:', districtName, response.data)
                        if (!response.data) {
                            throw new Error('地区编码数据为空')
                        }

                        // 遍历查找区县编码和坐标
                        for (const area of response.data) {
                            if (area.name === districtName) {
                                return {
                                    adcode: area.adcode,
                                    center: [area.lng, area.lat]
                                }
                            }
                        }
                        return null
                    } catch (error) {
                        console.error('获取区县编码失败:', error)
                        return null
                    }
                }

                // 获取区县边界数据
                const getDistrictBoundary = async (adcode) => {
                    try {
                        const response = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${adcode}.json`)
                        if (!response.data) {
                            throw new Error('区县边界数据为空')
                        }
                        return response.data
                    } catch (error) {
                        console.error('获取区县边界数据失败:', error)
                        return null
                    }
                }

                // 获取当前区县的编码和中心点
                const districtInfo = await getDistrictCode(this.currentArea)
                console.log(districtInfo, "districtInfo")
                if (!districtInfo) {
                    throw new Error('未找到区县编码')
                }

                // 获取区县边界数据
                const boundaryData = await getDistrictBoundary(districtInfo.adcode)
                if (!boundaryData) {
                    throw new Error('未找到区县边界数据')
                }

                console.log('区县中心点:', districtInfo.center)

                // 初始化区级地图
                const mapContainer = this.$refs.chartContainer
                const map = new AMap.Map(mapContainer, {
                    zoom: 12,
                    center: districtInfo.center,
                    viewMode: '3D',
                    key: 'e99261f883730cc7f3da5bfd30504a04'
                })

                // 等待地图加载完成
                await new Promise(resolve => {
                    map.on('complete', () => {
                        resolve()
                    })
                })

                this.showDistrictMap = true
                this.loading = false
                // 添加区级边界
                const district = new AMap.DistrictLayer.Province({
                    zIndex: 12,
                    adcode: [districtInfo.adcode],
                    depth: 2,
                    styles: {
                        'fill': function (properties) {
                            return 'rgba(128, 216, 255, 0.5)' // 设置为半透明蓝色
                        },
                        'province-stroke': 'rgba(41, 182, 246, 0.8)', // 半透明边框
                        'city-stroke': 'rgba(41, 182, 246, 0.8)', // 半透明边框
                        'county-stroke': 'rgba(41, 182, 246, 0.8)' // 半透明边框
                    }
                })
                map.add(district)

                // 添加区县名称标注
                const label = new AMap.Text({
                    text: this.currentArea,
                    anchor: 'center',
                    style: {
                        'background-color': 'rgba(255, 255, 255, 0.8)',
                        'border-radius': '4px',
                        'padding': '4px 8px',
                        'font-size': '14px',
                        'color': '#333'
                    },
                    position: districtInfo.center
                })
                map.add(label)

                // 确保地图定位到区县
                map.setCenter(districtInfo.center)
                map.setZoom(cityName === '香港特别行政区' ? 11 : cityName === '澳门特别行政区' ? 13 : cityName === '北京市' ? 9 : cityName === '上海市' ? 10 : cityName === '天津市' ? 10 : cityName === '重庆市' ? 9 : 11)

                // 添加水滴状标注点
                const addWaterDropMarkers = async () => {
                    try {
                        if (cityData && cityData.data) {
                            // 腾讯地图坐标转高德地图坐标
                            const convertCoordinate = (lng, lat) => {
                                const x_pi = 3.14159265358979324 * 3000.0 / 180.0
                                const x = lng
                                const y = lat
                                const z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi)
                                const theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi)
                                const lngs = z * Math.cos(theta) + 0.0065
                                const lats = z * Math.sin(theta) + 0.006
                                return {
                                    lng: lngs,
                                    lat: lats
                                }
                            }

                            // 创建标注点
                            cityData.data.forEach(point => {
                                console.log(provinceName, cityNames, this.currentArea, "1111111111111111111111111111111111")
                                if (
                                    point.registeredAddressCity === cityNames
                                    && point.registeredAddressDistrict === this.currentArea
                                ) {
                                    // 转换坐标
                                    const convertedPoint = convertCoordinate(point.registeredAddressLng, point.registeredAddressLat)

                                    // 创建水滴状图标
                                    const icon = new AMap.Icon({
                                        size: new AMap.Size(24, 24),
                                        image: require('@/assets/BI/shopMarker.png'),
                                        imageSize: new AMap.Size(24, 24)
                                    })

                                    // 创建标注点
                                    const marker = new AMap.Marker({
                                        position: [convertedPoint.lng, convertedPoint.lat],
                                        icon: icon,
                                        offset: new AMap.Pixel(-12, -12),
                                        title: point.name,
                                        animation: 'AMAP_ANIMATION_DROP'
                                    })

                                    // 添加点击事件
                                    marker.on('click', () => {
                                        console.log('点击标注点:', point)
                                        this.$emit('marker-click', { data: point, level: 'area' })
                                    })

                                    // 将标注点添加到地图
                                    map.add(marker)
                                }
                            })
                        }
                    } catch (error) {
                        console.error('添加标注点失败:', error)
                    }
                }

                // 调用添加标注点方法
                await addWaterDropMarkers()

                this.districtMap = map

            } catch (error) {
                console.error('初始化区级地图失败:', error)
                // 如果获取区县数据失败，使用默认配置
                const mapContainer = this.$refs.chartContainer
                const map = new AMap.Map(mapContainer, {
                    zoom: 11,
                    center: [116.397428, 39.90923],
                    viewMode: '3D'
                })

                const district = new AMap.DistrictLayer.Province({
                    zIndex: 12,
                    adcode: [cityName],
                    depth: 2,
                    styles: {
                        'fill': function (properties) {
                            return '#80d8ff'
                        },
                        'province-stroke': '#29b6f6',
                        'city-stroke': '#29b6f6',
                        'county-stroke': '#29b6f6'
                    }
                })
                map.add(district)

                this.districtMap = map
            }
        },
        async handleBack() {
            try {
                this.loading = true

                if (this.mapHistory.length === 0) {
                    throw new Error('没有历史记录')
                }

                // 如果当前是区级地图，需要先销毁地图实例
                if (this.showDistrictMap && this.districtMap) {
                    this.districtMap.destroy()
                    this.districtMap = null
                    this.showDistrictMap = false
                }

                // 从历史记录中获取上一级数据
                const previousState = this.mapHistory.pop()
                console.log('历史记录状态:', previousState)

                // 使用历史记录中的数据
                this.currentLevel = previousState.level
                this.currentArea = previousState.area
                this.mapData = previousState.data

                // 如果是直辖市或特别行政区，更新isMunicipality状态
                this.isMunicipality = ['北京市', '上海市', '天津市', '重庆市', '香港特别行政区', '澳门特别行政区', '台湾省'].includes(this.currentArea)

                // 等待一帧以确保状态更新
                await this.$nextTick()

                // 如果是返回到中国地图，重新初始化
                if (this.currentLevel === 'china') {
                    try {
                        console.log('开始加载中国地图数据')

                        // 1. 重新加载中国地图数据
                        const response = await axios.get('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
                        if (!response.data) {
                            throw new Error('中国地图数据为空')
                        }

                        console.log('中国地图数据加载成功')

                        // 2. 添加淡出动画
                        if (this.chart) {
                            this.chart.setOption({
                                animation: true,
                                animationDuration: 300,
                                animationEasing: 'cubicOut'
                            })
                            // 等待动画完成
                            await new Promise(resolve => setTimeout(resolve, 300))
                        }

                        // 3. 销毁当前图表实例
                        if (this.chart) {
                            this.chart.dispose()
                            this.chart = null
                        }

                        // 4. 保存并注册地图
                        this.guojiaData = response
                        echarts.registerMap('china', response.data)
                        console.log('中国地图注册成功')

                        // 5. 生成新的地图数据
                        const chinaData = {
                            name: '中国',
                            children: (await this.getEMapData('getRegionMapData', '', 'country', '', '', '', '')) || response.data.features.map(feature => ({
                                name: feature.properties.name,
                                value: Math.floor(Math.random() * 1000)
                            })),
                        }

                        // 6. 更新状态
                        this.currentLevel = 'china'
                        this.currentArea = '中国'
                        this.mapData = chinaData

                        console.log('返回中国地图数据:', { name: '中国', level: 'country' })
                        this.$emit('map-click', { name: '中国', level: 'country' })

                        console.log('返回中国地图数据:', {
                            level: this.currentLevel,
                            area: this.currentArea,
                            mapData: this.mapData
                        })

                        // 7. 重新初始化图表
                        this.initChart()

                        // 8. 添加淡入动画并渲染
                        const option = this.getMapOption('china', 1, '30%')
                        this.chart.setOption(option, {
                            animation: true,
                            animationDuration: 300,
                            animationEasing: 'cubicIn'
                        })
                    } catch (error) {
                        console.error('重新加载中国地图数据失败:', error)
                        throw error
                    }
                } else {
                    // 如果不是中国地图，直接渲染
                    let mapName = this.currentArea
                    let zoom = 1
                    let top = '8%'

                    // 根据当前层级和地区调整地图参数
                    if (this.currentLevel === 'province') {
                        if (this.isMunicipality) {
                            mapName = this.currentArea
                            // zoom = this.currentArea === '香港特别行政区' ? 2.5 : this.currentArea === '澳门特别行政区' ? 2.5 : 1
                            // top = this.currentArea === '香港特别行政区' ? '15%' : this.currentArea === '澳门特别行政区' ? '15%' : '8%'
                            // 根据省份调整缩放和位置
                            zoom = this.currentArea === '海南省' ? 5 : this.currentArea === '香港特别行政区' || this.currentArea === '澳门特别行政区' || this.currentArea === '台湾省' ? 1 : 1
                            top = this.currentArea === '海南省' ? '100%' : this.currentArea === '香港特别行政区' || this.currentArea === '澳门特别行政区' || this.currentArea === '台湾省' ? '15%' : '8%'

                        } else {
                            mapName = this.currentArea
                            zoom = this.currentArea === '海南省' ? 5 : this.currentArea === '香港特别行政区' || this.currentArea === '澳门特别行政区' || this.currentArea === '台湾省' ? 1 : 1
                            top = this.currentArea === '海南省' ? '100%' : this.currentArea === '香港特别行政区' || this.currentArea === '澳门特别行政区' || this.currentArea === '台湾省' ? '15%' : '8%'

                        }
                    } else if (this.currentLevel === 'city') {
                        mapName = this.currentArea
                    }

                    const option = this.getMapOption(mapName, zoom, top)
                    console.log('返回上一级地图数据:', { name: this.currentArea, level: this.currentLevel })
                    this.$emit('map-click', { name: this.currentArea, level: this.currentLevel })

                    // 重新初始化echarts实例
                    if (!this.chart) {
                        this.initChart()
                    }

                    this.chart.setOption(option, {
                        animation: true,
                        animationDuration: 300,
                        animationEasing: 'cubicOut'
                    })
                }
            } catch (error) {
                console.error('返回上一级失败:', error)
                this.error = '返回上一级失败'
            } finally {
                this.loading = false
            }
        },
        getProvinceByCity(cityName) {
            console.log('查找城市所属省份:', cityName)
            console.log('当前地区编码数据:', this.areaCodes)

            // 从城市名获取所属省份
            for (const [provinceName] of Object.entries(this.areaCodes.provinces)) {
                const cities = this.areaCodes.cities[provinceName] || []
                // console.log(`检查省份 ${provinceName} 的城市列表:`, cities)
                if (cities.includes(cityName)) {
                    console.log(`找到城市 ${cityName} 所属的省份:`, provinceName)
                    return provinceName
                }
            }
            console.log(`未找到城市 ${cityName} 所属的省份`)
            return null
        }
    },
    beforeDestroy() {
        if (this.chart) {
            this.chart.dispose()
            this.chart = null
        }
        if (this.districtMap) {
            this.districtMap.destroy()
            this.districtMap = null
        }
    }
}
</script>

<style scoped>
.map-container {
    width: 100%;
    height: calc(100vh - 130px);
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}

.chart-container {
    width: 100%;
    height: calc(100% - 30px);
    position: absolute;
    top: 0;
    left: 0;
}

.district-map {
    background-color: #fff;
}

.map-header-left {
    position: absolute;
    width: -webkit-fill-available;
    top: 15%;
    left: 27.8%;
    z-index: 10000;
}

.map-header {
    position: absolute;
    width: -webkit-fill-available;
    top: 15%;
    left: 67.8%;
    z-index: 10000;
}

.back-button {
    padding: 8px 16px;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    color: #333;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.back-button:hover {
    background-color: #f5f5f5;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 24px;
    color: #666;
    font-weight: 600;
}

.error {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: red;
    font-size: 16px;
}
</style>